//
//  MasterViewController.m
//  SeplitDemo
//
//  Created by 信恩世通 on 2017/8/1.
//  Copyright © 2017年 Xiyuekeji. All rights reserved.
//

// controller
#import "MasterViewController.h"
#import "DetailViewController.h"

// view
#import "CollectionHeaderView.h"
#import "CollectionViewItemCell.h"

// model
#import "GoodsListModel.h"
#import "CategoryReq.h"

@interface MasterViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *layout;
@property (strong, nonatomic) NSMutableArray *dataSource;

@end

@implementation MasterViewController

static NSString * const CollectionHeaderViewID = @"CollectionHeaderView";
static NSString * const CollectionViewItemCellID = @"CollectionViewItemCell";

#pragma mark - **** lazy loading ****

static NSString * const dataSourceData = @"dataSourceData";

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        NSUserDefaults *uDefault = [NSUserDefaults standardUserDefaults];
        NSArray *dataSourceArr = [uDefault objectForKey:dataSourceData];
        if (dataSourceArr.count) {
            _dataSource = [GoodsListModel mj_objectArrayWithKeyValuesArray:dataSourceArr];
        }
    }
    return _dataSource;
}

- (UICollectionViewFlowLayout *)layout {
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        _layout.itemSize = CGSizeMake(100, 100);
        _layout.minimumLineSpacing = 10.0;
        _layout.minimumInteritemSpacing = 0.0;
        _layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        _layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 30);
    }
    return _layout;
}

#pragma mark - **** system callback ****

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavigationBar];
    
    [self commonInit];
    [self loadGoodsListData];
}


#pragma mark - **** parivate method ****

/** 设置UI */
- (void)commonInit {
    
    self.view.backgroundColor = COLOR_BG;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:self.layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = COLOR_BG;
    
    // register Cell & header
    [_collectionView registerClass:[CollectionViewItemCell class] forCellWithReuseIdentifier:CollectionViewItemCellID];
    _collectionView.showsVerticalScrollIndicator = YES;
    [_collectionView registerClass:[CollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CollectionHeaderViewID];
    
    // add to superView
    [self.view addSubview:_collectionView];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

/** 设置导航栏 */
- (void)setupNavigationBar {
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
    self.navigationItem.rightBarButtonItem = addButton;
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}

- (void)insertNewObject:(id)sender {
//    if (!self.objects) {
//        self.objects = [[NSMutableArray alloc] init];
//    }
//    [self.objects insertObject:[NSDate date] atIndex:0];
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}


#pragma mark - **** UITableViewDataSource ****

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSource.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 6;
            break;
        case 1:
            return 16;
            break;
        case 2:
            return 10;
            break;
            
        default:
            break;
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CollectionViewItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewItemCellID forIndexPath:indexPath];
    GoodsListModel *sectionModel = self.dataSource[indexPath.section];
    GoodsTopicsModel *topicsModel = sectionModel.GoodsTopics;
    cell.goodsItemDic = topicsModel.GoodsArray[indexPath.row];;
    
    return cell;
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        CollectionHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CollectionHeaderViewID forIndexPath:indexPath];
        GoodsListModel *sectionModel = self.dataSource[indexPath.section];
        header.titleStr = sectionModel.AdvertName;
        return header;
    } else {
        return nil;
    }
    
}


#pragma mark - **** UITableViewDelegate ****

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CollectionViewItemCell *cell = (CollectionViewItemCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    NSMutableDictionary *goodsDic = [cell.goodsItemDic mutableCopy];
    
    if ([self.delegate respondsToSelector:@selector(addSelectedGoodsDic:)]) {
        [self.delegate addSelectedGoodsDic:goodsDic];
    }
}


#pragma mark - **** network request ****

// 获取商品列表接口
- (void)loadGoodsListData {
    
    CategoryReq *model = [[CategoryReq alloc] init];
    model.API = GoodsListAPI;
    
    WS(weakSelf)
    [AFNRequestManager POST:AFNBaseURL parameter:model success:^(id response, NSInteger resposeCode) {
        [MBProgressHUD hideFromView:weakSelf.view];
        
        if (![response isKindOfClass:[NSDictionary class]]) {
            DBLog(@"商业商品列表->数据格式错误");
            return ;
        }
        
        NSDictionary *status = response[@"Status"];
        
        if (1 != [status[@"StatusCode"] integerValue]) {
            DBLog(@"商业商品列表->状态码错误");
            return ;
        }
        
        
        NSDictionary *data = response[@"Result"];
        NSArray *listArray = data[@"List"];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSUserDefaults *uDefault = [NSUserDefaults standardUserDefaults];
            
            [uDefault setObject:listArray forKey:dataSourceData];
            [uDefault setBool:NO forKey:isAppFirstStart];
        });
        
        weakSelf.dataSource = [GoodsListModel mj_objectArrayWithKeyValuesArray:listArray];
        
        [weakSelf.collectionView reloadData];
        
    } failure:^(NSError *error, NSString *errorMsg) {
        [MBProgressHUD hideFromView:weakSelf.view];
    }];
}


@end
